﻿using Dong.Model;
using Stote.Helpers;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace Stote.Forms
{
    public partial class FrmStorageRecord : Form
    {
        Dong.BLL.StorageRecord storageRecordBLL = new Dong.BLL.StorageRecord();
        Dong.BLL.StoreArea storeAreaBLL = new Dong.BLL.StoreArea();
        Dong.BLL.Inventory inventoryBLL = new Dong.BLL.Inventory();

        #region 构造函数
        public FrmStorageRecord()
        {
            InitializeComponent();
            Bind();

            btnSearch.Click += btnSearch_Click;
            btnAdd.Click += btnAdd_Click;
            btnInventory.Click += BtnInventory_Click;

            ucPager1.PageChanged += UcPager1_PageChanged;

            dataGridView1.CellPainting += dataGridView1_CellPainting;
            dataGridView1.CellMouseClick += dataGridView1_CellMouseClick;
            dataGridView1.CellFormatting += dataGridView1_CellFormatting;

            dtpIncomeStart.ValueChanged += DtpIncomeStart_ValueChanged;
            dtpIncomeEnd.ValueChanged += DtpIncomeEnd_ValueChanged;

            dtpIncomeStart.Format = DateTimePickerFormat.Custom;
            dtpIncomeStart.CustomFormat = " ";
            dtpIncomeEnd.Format = DateTimePickerFormat.Custom;
            dtpIncomeEnd.CustomFormat = " ";
        }
        #endregion

        #region 日期格式化
        private void DtpIncomeEnd_ValueChanged(object sender, EventArgs e)
        {
            dtpIncomeEnd.Format = DateTimePickerFormat.Custom;
            dtpIncomeEnd.CustomFormat = "yyyy-MM-dd";
        }

        private void DtpIncomeStart_ValueChanged(object sender, EventArgs e)
        {
            dtpIncomeStart.Format = DateTimePickerFormat.Custom;
            dtpIncomeStart.CustomFormat = "yyyy-MM-dd";
        }
        #endregion

        #region 数据绑定
        private void Bind()
        {
            DataSet ds = storeAreaBLL.GetList(" Status=0"); // 拿到数据集
            DataTable dt = ds.Tables[0]; // 拿到数据集中的一个表
            DataRow dr = dt.NewRow(); // 创建新行，保存是“全部”
            // 给新行添加两列StoreAreaId和StoreAreaName，注意这两列要和表中的列同名
            dr["StoreAreaId"] = -1;
            dr["StoreAreaName"] = "全部";
            dt.Rows.InsertAt(dr, 0);
            cbStoreArea.DataSource = dt; // 注意一下：DataSource数据源，绑定datatable不要绑定dataset
            cbStoreArea.DisplayMember = "StoreAreaName";  // 显示成员，用户看到文本
            cbStoreArea.ValueMember = "StoreAreaId"; // 数据成员，程序使用的数据

            List<Dong.Model.Status> list = new List<Dong.Model.Status>() {
                new Dong.Model.Status(){Id=-1,Name="全部"},
                new Dong.Model.Status(){Id=0,Name="正常"},
                new Dong.Model.Status(){Id=1,Name="禁用"},
            };
            cbStatus.DataSource = list;
            cbStatus.DisplayMember = "Name";
            cbStatus.ValueMember = "Id";
        }
        #endregion

        #region 打开添加窗体
        private void btnAdd_Click(object sender, EventArgs e)
        {
            // 参数1：0表示添加，非零表示是编辑。参数2：当前窗体FrmStorageRecord。目的：为了窗体之间跳转
            FrmStorageRecordAddAndEdit form = new FrmStorageRecordAddAndEdit(0, this);
            if (form.ShowDialog() == DialogResult.OK)
            {
                btnSearch.PerformClick();
            }
        }

        private void BtnInventory_Click(object sender, EventArgs e)
        {
            FrmMain mainForm = this.ParentForm as FrmMain;
            mainForm.ToggleSelected("库存盘点");
            mainForm.OpenForm(new FrmInventory(), "库存盘点");
        }
        #endregion

        #region 查询及数据绑定
        private void UcPager1_PageChanged(int pageSize, int currentPage, out int totalCount)
        {
            int startIndex = (currentPage - 1) * pageSize + 1;
            int endIndex = startIndex + pageSize - 1;
            string strWhere = $" 1=1";
            if (!string.IsNullOrEmpty(txtProductName.Text.Trim()))
                strWhere += $" AND ProductName LIKE '%{txtProductName.Text.Trim()}%'";
            if (Convert.ToInt32(cbStoreArea.SelectedValue) != -1)
                strWhere += $" AND StoreAreaId={Convert.ToInt32(cbStoreArea.SelectedValue)}";
            if (Convert.ToInt32(cbStatus.SelectedValue) != -1)
                strWhere += $" AND Status={Convert.ToInt32(cbStatus.SelectedValue)}";
            if (!string.IsNullOrWhiteSpace(dtpIncomeStart.Text) && !string.IsNullOrWhiteSpace(dtpIncomeEnd.Text))
            {
                strWhere += $" AND IncomeTime>='{Convert.ToDateTime(dtpIncomeStart.Text).ToString("yyyy-MM-dd")} 00:00:00' AND IncomeTime<='{Convert.ToDateTime(dtpIncomeEnd.Text).ToString("yyyy-MM-dd")} 23:59:59'";
            }
            if (!string.IsNullOrWhiteSpace(dtpIncomeStart.Text) && string.IsNullOrWhiteSpace(dtpIncomeEnd.Text))
            {
                strWhere += $" AND IncomeTime>='{Convert.ToDateTime(dtpIncomeStart.Text).ToString("yyyy-MM-dd")} 00:00:00'";
            }
            if (string.IsNullOrWhiteSpace(dtpIncomeStart.Text) && !string.IsNullOrWhiteSpace(dtpIncomeEnd.Text))
            {
                strWhere += $" AND IncomeTime<='{Convert.ToDateTime(dtpIncomeEnd.Text).ToString("yyyy-MM-dd")} 23:59:59'";
            }

            DataSet ds = storageRecordBLL.GetListByPage(strWhere, "CreateTime DESC", startIndex, endIndex);

            totalCount = storageRecordBLL.GetRecordCount(strWhere);
            dataGridView1.DataSource = ds.Tables[0];

            DataGridViewHelper.DataGridStyle(dataGridView1);

            dataGridView1.Columns["Row"].Visible = false;
            dataGridView1.Columns["StoreId"].Visible = false;
            dataGridView1.Columns["StoreAreaId"].Visible = false;
            dataGridView1.Columns["ProductId"].Visible = false;
            dataGridView1.Columns["Remark"].Visible = false;
            dataGridView1.Columns["Status"].Visible = false;
            dataGridView1.Columns["CreateUserId"].Visible = false;
            dataGridView1.Columns["LastUpdateUserId"].Visible = false;

            dataGridView1.Columns["RecordId"].HeaderText = "主键";
            dataGridView1.Columns["StoreId"].HeaderText = "仓库Id";
            dataGridView1.Columns["StoreName"].HeaderText = "仓库名称";
            dataGridView1.Columns["StoreAreaId"].HeaderText = "区域Id";
            dataGridView1.Columns["StoreAreaName"].HeaderText = "区域名称";
            dataGridView1.Columns["ProductId"].HeaderText = "产品Id";
            dataGridView1.Columns["ProductName"].HeaderText = "产品名称";
            dataGridView1.Columns["Amount"].HeaderText = "产品数量";
            dataGridView1.Columns["IncomeTime"].HeaderText = "入库时间";
            dataGridView1.Columns["Remark"].HeaderText = "备注";
            dataGridView1.Columns["Status"].HeaderText = "状态";
            dataGridView1.Columns["StatusName"].HeaderText = "状态";
            dataGridView1.Columns["CreateUserId"].HeaderText = "创建人Id";
            dataGridView1.Columns["CreateUserName"].HeaderText = "创建人";
            dataGridView1.Columns["CreateTime"].HeaderText = "创建时间";
            dataGridView1.Columns["LastUpdateUserId"].HeaderText = "修改人Id";
            dataGridView1.Columns["LastUpdateUserName"].HeaderText = "修改人";
            dataGridView1.Columns["LastUpdateTime"].HeaderText = "修改时间";

            dataGridView1.Columns["IncomeTime"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            dataGridView1.Columns["CreateTime"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            dataGridView1.Columns["LastUpdateTime"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";

            if (!dataGridView1.Columns.Contains("Operator"))
            {
                dataGridView1.Columns.Add("Operator", "操作");
                dataGridView1.Columns["RecordId"].Width = 70;
                dataGridView1.Columns["Amount"].Width = 120;
                dataGridView1.Columns["IncomeTime"].Width = 220;
                dataGridView1.Columns["CreateUserName"].Width = 90;
                dataGridView1.Columns["CreateTime"].Width = 220;
                dataGridView1.Columns["LastUpdateUserName"].Width = 90;
                dataGridView1.Columns["LastUpdateTime"].Width = 220;
                dataGridView1.Columns["Operator"].Width = 160;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            ucPager1.CurrentPage = 1;
            ucPager1.TriggerPageChanged();
        }
        #endregion

        #region 网格添加列，格式化
        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                if (dataGridView1.Columns[e.ColumnIndex].HeaderText == "操作")
                {
                    StringFormat sf = StringFormat.GenericDefault.Clone() as StringFormat;
                    sf.FormatFlags = StringFormatFlags.DisplayFormatControl;
                    sf.Alignment = StringAlignment.Center;
                    sf.LineAlignment = StringAlignment.Center;
                    sf.Trimming = StringTrimming.EllipsisCharacter;

                    e.PaintBackground(e.CellBounds, false);

                    Font myFont = new Font("微软雅黑", 10F, FontStyle.Underline, GraphicsUnit.Point, 134);
                    SizeF sizeSta = e.Graphics.MeasureString("启用", myFont);
                    SizeF sizeDel = e.Graphics.MeasureString("删除", myFont);
                    SizeF sizeMod = e.Graphics.MeasureString("编辑", myFont);
                    float totalWidth = (sizeSta.Width + sizeDel.Width + sizeMod.Width);

                    float fSta = sizeSta.Width / totalWidth;
                    float fDel = sizeDel.Width / totalWidth;
                    float fMod = sizeMod.Width / totalWidth;

                    var rect1 = new RectangleF(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width * fSta, e.CellBounds.Height);
                    var rect2 = new RectangleF(rect1.Right, e.CellBounds.Top, e.CellBounds.Width * fDel, e.CellBounds.Height);
                    var rect3 = new RectangleF(rect2.Right, e.CellBounds.Top, e.CellBounds.Width * fMod, e.CellBounds.Height);

                    e.Graphics.DrawString("启用", myFont, new SolidBrush(Color.FromArgb(1, 62, 153)), rect1, sf);
                    e.Graphics.DrawString("删除", myFont, Brushes.Red, rect2, sf);
                    e.Graphics.DrawString("编辑", myFont, new SolidBrush(Color.FromArgb(1, 62, 153)), rect3, sf);

                    e.Handled = true;
                }
            }
        }

        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                Point curPosition = e.Location;
                if (dataGridView1.Columns[e.ColumnIndex].HeaderText == "操作")
                {
                    Graphics g = dataGridView1.CreateGraphics();
                    Font myFont = new Font("微软雅黑", 10F, FontStyle.Underline, GraphicsUnit.Point, 134);

                    SizeF sizeSta = g.MeasureString("启用", myFont);
                    SizeF sizeDel = g.MeasureString("删除", myFont);
                    SizeF sizeMod = g.MeasureString("编辑", myFont);
                    float totalWidth = (sizeSta.Width + sizeDel.Width + sizeMod.Width);

                    float fSta = sizeSta.Width / totalWidth;
                    float fDel = sizeDel.Width / totalWidth;
                    float fMod = sizeMod.Width / totalWidth;

                    var rectTotal = new Rectangle(0, 0, dataGridView1.Columns[e.ColumnIndex].Width, dataGridView1.Rows[e.RowIndex].Height);
                    var rectSta = new RectangleF(rectTotal.Left, rectTotal.Top, rectTotal.Width * fSta, rectTotal.Height);
                    var rectDel = new RectangleF(rectSta.Right, rectTotal.Top, rectTotal.Width * fDel, rectTotal.Height);
                    var rectMod = new RectangleF(rectDel.Right, rectTotal.Top, rectTotal.Width * fMod, rectTotal.Height);

                    int id = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["RecordId"].Value);
                    Dong.Model.StorageRecord model = storageRecordBLL.GetModel(id);

                    if (rectSta.Contains(curPosition))
                    {
                        if (model.Status == 0)
                        {
                            MessageBox.Show("数据正常，不必再次启用！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        DialogResult dr = MessageBox.Show("你确定要启用此条记录吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dr == DialogResult.Yes)
                        {
                            model.Status = 0;
                            model.LastUpdateUserId = FrmLogin.CurrentUser.UserId;
                            model.LastUpdateTime = DateTime.Now;
                            storageRecordBLL.Update(model);
                            UpdateInventory(model.StoreAreaId, model.ProductId, model.Amount);
                            btnSearch.PerformClick();
                        }
                    }

                    if (rectDel.Contains(curPosition))
                    {
                        if (model.Status == 1)
                        {
                            MessageBox.Show("已禁用的数据，不必再次删除！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        DialogResult dr = MessageBox.Show("你确定要删除此条记录吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dr == DialogResult.Yes)
                        {
                            model.Status = 1;
                            model.LastUpdateUserId = FrmLogin.CurrentUser.UserId;
                            model.LastUpdateTime = DateTime.Now;
                            storageRecordBLL.Update(model);
                            UpdateInventory(model.StoreAreaId, model.ProductId, -model.Amount);
                            btnSearch.PerformClick();
                        }
                    }

                    if (rectMod.Contains(curPosition))
                    {
                        if (model.Status == 1)
                        {
                            MessageBox.Show("禁用的数据不能编辑！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        FrmStorageRecordAddAndEdit form = new FrmStorageRecordAddAndEdit(id, this);
                        if (form.ShowDialog() == DialogResult.OK)
                        {
                            btnSearch.PerformClick();
                        }
                    }
                }
            }
        }

        private void UpdateInventory(int storeAreaId, int productId, int amount)
        {
            // 查询库存盘点表中是否已经存在某个区域的某个产品，如果存在，则更新产品数量
            DataSet ds = inventoryBLL.GetList($" Status=0 AND ProductId={productId} AND StoreAreaId={storeAreaId}");
            if (ds.Tables[0].Rows.Count > 0) // 存在
            {
                // 更新库存盘点表中的产品数量
                int inventoryId = Convert.ToInt32(ds.Tables[0].Rows[0]["InventoryId"]);
                Dong.Model.Inventory inventoryModel = inventoryBLL.GetModel(inventoryId);
                inventoryModel.Amount += amount;
                inventoryModel.LastUpdateUserId = FrmLogin.CurrentUser.UserId;
                inventoryModel.LastUpdateTime = DateTime.Now;
                inventoryBLL.Update(inventoryModel);
            }
            else // 不存在，则在库存盘点表插入一条数据。
            {
                Dong.Model.StoreArea storeAreaModel = storeAreaBLL.GetModel(storeAreaId);
                Dong.Model.Inventory inventoryModel = new Dong.Model.Inventory()
                {
                    ProductId = productId,
                    StoreId = storeAreaModel.StoreId,
                    StoreAreaId = storeAreaId,
                    Remark = "自动盘点",
                    Amount = amount,
                    CreateUserId = FrmLogin.CurrentUser.UserId,
                };
                inventoryBLL.Add(inventoryModel);
            }
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("StatusName"))
            {
                if (e.Value.ToString() == "正常")
                {
                    e.CellStyle.ForeColor = Color.FromArgb(1, 62, 153);
                }
                else
                {
                    e.CellStyle.ForeColor = Color.Red;
                }
            }
        }
        #endregion
    }
}
